#include "BoxCollider.h"

#include "Math/Math.h"
#include "Math/BoundingBox.h"

#include "Scene/SceneNode.h"

SBoundingBox RBoxCollider::GetWorldAABB()
{
    SVec3 NodeWorldPos = GetNode()->GetWorldPosition();
    SQuat NodeWorldRot = GetNode()->GetWorldRotation();

    //计算旋转后的X轴
    SVec3 RotatedX = NodeWorldRot*SVec3(HalfExtent.X, 0.0f, 0.0f);
    //计算旋转后的Y轴
    SVec3 RotatedY = NodeWorldRot*SVec3(0.0f, HalfExtent.Y, 0.0f);
    //计算旋转后的Z轴
    SVec3 RotatedZ = NodeWorldRot*SVec3(0.0f, 0.0f, HalfExtent.Z);

    //计算旋转后8个顶点，只考虑旋转
    SVec3 RotateVertex[8];
    RotateVertex[0] = RotatedX  + RotatedY + RotatedZ ;
    RotateVertex[1] = RotatedX  + RotatedY - RotatedZ ;
    RotateVertex[2] = RotatedX  - RotatedY + RotatedZ ;
    RotateVertex[3] = RotatedX  - RotatedY - RotatedZ ;

    RotateVertex[4] = -RotateVertex[0];
    RotateVertex[5] = -RotateVertex[1];
    RotateVertex[6] = -RotateVertex[2];
    RotateVertex[7] = -RotateVertex[3];
    

    //计算包围盒
    SBoundingBox AABB;
    AABB.Min = RotateVertex[0];

    for (int i = 1; i < 8; i++)
    {
        AABB.Min.X = CMath::Min(AABB.Min.X, RotateVertex[i].X);
        AABB.Min.Y = CMath::Min(AABB.Min.Y, RotateVertex[i].Y);
        AABB.Min.Z = CMath::Min(AABB.Min.Z, RotateVertex[i].Z);
    }
    AABB.Max=-AABB.Min;

    //考虑位移
    SVec3 Offset=NodeWorldRot*Center+ NodeWorldPos;
    AABB.Min += Offset;
    AABB.Max += Offset;

    return AABB;
}